package com.mystnihon.tdroid.view.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import ca.benow.transmission.model.TorrentFile;
import ca.benow.transmission.model.TorrentStatus;

import com.actionbarsherlock.app.SherlockListFragment;
import com.mystnihon.tdroid.R;

public class TorrentFileFragment extends SherlockListFragment {
	TorrentStatus mTorrentStatus;
	TorrentFileAdapter mAdapter;

	public TorrentFileFragment(TorrentStatus lTorrentStatus) {
		mTorrentStatus = lTorrentStatus;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		mAdapter = new TorrentFileAdapter(getSherlockActivity());
		setListAdapter(mAdapter);
		refreshListDataSet();
		super.onActivityCreated(savedInstanceState);
	}

	public void refresh(TorrentStatus lTorrentStatus) {
		mTorrentStatus = lTorrentStatus;
		refreshListDataSet();
	}

	private void refreshListDataSet() {
		if (mTorrentStatus != null && mAdapter != null) {
			mAdapter.setTorrentFiles(mTorrentStatus.getFiles());
		}
	}

	class ViewHolder {
		TextView mFilename;
		TextView mSize;
		TextView mCompleted;
	}

	class TorrentFileAdapter extends BaseAdapter {

		Context mContext;
		LayoutInflater inflater;
		ArrayList<TorrentFile> mFiles;

		public TorrentFileAdapter(Context context) {
			mContext = context;
			mFiles = new ArrayList<TorrentFile>();
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void setTorrentFiles(ArrayList<TorrentFile> files) {
			if (files != null) {
				mFiles = files;
				notifyDataSetChanged();
			}
		}

		@Override
		public int getCount() {
			return mFiles.size();
		}

		@Override
		public TorrentFile getItem(int position) {

			return mFiles.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.listitem_torrent_file, null);
				holder.mFilename = (TextView) convertView.findViewById(R.id.listitem_torrent_filename);
				holder.mSize = (TextView) convertView.findViewById(R.id.listitem_torrent_size);
				holder.mCompleted = (TextView) convertView.findViewById(R.id.listitem_torrent_completed);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			TorrentFile file = getItem(position);
			holder.mFilename.setText(file.getName());
			holder.mSize.setText(TorrentFile.prettifysize(file.getSize()));
			holder.mCompleted.setText(TorrentFile.prettifysize(file.getCompleted()));
			return convertView;
		}

	}
}